import { updateNutrition, getNewsList }  from '../../http/api';
// index.js
Page({
  data:{
    periodicals: [],
    nutrients: [
      { id: 'protein', name: '蛋白(g)', value: '0', percentage: '0', goal: 150, image: '/images/protein.png' },
      { id: 'carbs', name: '碳水(g)', value: '0', percentage: '0', goal: 150, image: '/images/carbs.png' },
      { id: 'fat', name: '脂肪(g)', value: '0', percentage: '0', goal: 150, image: '/images/fat.png' },
      { id: 'calories', name: '热量(kcal)', value: '0', percentage: '0', goal: 150, image: '/images/water.png' }
    ],
    meals: [
      { id: '1', name: '早餐', image: 'https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/morning.png' },
      { id: '2', name: '午餐', image: 'https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/afternoon.png' },
      { id: '3', name: '晚餐', image: 'https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/night.png' },
      { id: '4', name: '加餐', image: 'https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/plusfood.png' }
    ],
    dailyGoals: {
      protein: 150,  // 默认值
      carbs: 300,
      fat: 70,
      calories: 2000
    },
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    selectedDate: new Date().toISOString().split('T')[0] // 默认今天
  },
  onItemClick(e) {
    const itemId = e.currentTarget.dataset.id; 
    wx.navigateTo({
      url: `/pages/news/news?itemId=${itemId}`
    })
  },
  // 点击餐次项时跳转到对应页面
  onMealTap: function(e) {
    const mealId = e.currentTarget.dataset.id; // 获取餐次 ID
    const mealName = e.currentTarget.dataset.name; // 获取餐次名称

    // 跳转到目标页面，并传递参数
    wx.navigateTo({
      url: `/pages/meal/meal?mealId=${mealId}&mealName=${mealName}`
    });
  },
  navigateToCalorieQuery: function() {
    wx.navigateTo({
      url: '/pages/heat/heat', // 注意这里的路径需要与app.json中配置的一致
    });
  },

  onLoad() {    
    this.loadNutritionData();
    this.loadNewsData();
  },

  onShow() {
    this.onLoad();
  },
  
  onPullDownRefresh() {
    console.log('下拉刷新');
    
    // 重置数据
    this.setData({
      page: 1,
      periodicals: [],
      hasMore: true
    }, () => {
      // 重新加载营养数据和新闻数据
      this.loadNutritionData();
      this.loadNewsData();
      
      // 停止下拉刷新动画
      wx.stopPullDownRefresh();
    });
  },

  onDateChange(e) {
    this.setData({
      selectedDate: e.detail.value
    }, () => {
      this.loadNutritionData();
    });
  },

  loadNutritionData() {
    const userId = wx.getStorageSync('userInfo').userId;
    if (!userId) return;

    wx.showLoading({ title: '加载中...' });

    updateNutrition(userId,this.data.selectedDate)
    .then((res) => {
      if(res.data.success) {                  
        this.updateNutritionDisplay(res.data);
      } else {
        wx.hideLoading(); 
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });      
      }
    })
    .catch((err) => {
      wx.hideLoading();
      wx.showToast({
        title: '加载营养数据失败',
        icon: 'none'
      });      
    });
  },

  loadNewsData() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });
    getNewsList(this.data.page, this.data.pageSize)
      .then(res => {        
        const newPeriodicals = res        
        .map(item => ({
          id: item.newsId,
          title: item.title,
          publishTime: item.publishTime,
          img: item.image ? 'https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/' + item.image : '',
          category: item.category,
          commentCount: item.commentCount
        }));
        // 判断是否还有更多数据
        const hasMore = res.length === this.data.pageSize;
        this.setData({
          periodicals: [...this.data.periodicals, ...newPeriodicals],
          page: this.data.page + 1,
          hasMore: hasMore,
          loading: false
        });
      })
      .catch(err => {
        console.error('加载新闻失败', err);
        this.setData({ loading: false });
      });
  },

  updateNutritionDisplay(summaryData) {
    const totalSummary = summaryData.total || {
      totalCalories: 0,
      totalProtein: 0,
      totalFat: 0,
      totalCarbohydrate: 0
    };
         
    const dailyGoals = summaryData.goals;
    this.setData({
      nutrients: [
        { 
          id: 'protein', 
          name: '蛋白(g)', 
          value: totalSummary.totalProtein.toFixed(1), 
          percentage: ((totalSummary.totalProtein / dailyGoals.proteinGoal) * 100).toFixed(0),
          image: '/images/protein.png' 
        },
        { 
          id: 'carbs', 
          name: '碳水(g)', 
          value: totalSummary.totalCarbohydrate.toFixed(1), 
          percentage: ((totalSummary.totalCarbohydrate / dailyGoals.carbohydrateGoal) * 100).toFixed(0),
          image: '/images/carbs.png' 
        },
        { 
          id: 'fat', 
          name: '脂肪(g)', 
          value: totalSummary.totalFat.toFixed(1), 
          percentage: ((totalSummary.totalFat / dailyGoals.fatGoal) * 100).toFixed(0),
          image: '/images/fat.png' 
        },
        { 
          id: 'calories', 
          name: '热量(kcal)', 
          value: `${totalSummary.totalCalories.toFixed(0)}/${dailyGoals.caloriesGoal.toFixed(0)}`, 
          percentage: ((totalSummary.totalCalories / dailyGoals.caloriesGoal) * 100).toFixed(0),
          image: '/images/calories.png' 
        }
      ]
    });
    
    wx.hideLoading();
  },
  onReachBottom() {    
    this.loadNewsData();
  },

  onItemClick(e) {
    const itemId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/news/news?itemId=${itemId}`
    });
  },

})

